import atexit
from app.hardware.relay_controller import relay_controller
import logging

logger = logging.getLogger(__name__)

class GPIOManager:
    """GPIO 资源管理器"""
    
    def __init__(self):
        self._initialized = False
    
    def initialize(self):
        """初始化 GPIO"""
        if not self._initialized:
            try:
                relay_controller.initialize()
                # 注册退出清理函数
                atexit.register(self.cleanup)
                self._initialized = True
                logger.info("GPIO管理器初始化完成")
            except Exception as e:
                logger.error(f"GPIO管理器初始化失败: {e}")
                # 在非测试环境下，如果初始化失败可以抛出异常
                if not getattr(relay_controller, '_is_testing', False):
                    raise
    
    def cleanup(self):
        """清理 GPIO 资源"""
        relay_controller.cleanup()
        logger.info("GPIO资源清理完成")

# 全局 GPIO 管理器
gpio_manager = GPIOManager()